package pzl.com.threadrelated;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class NotifyWorkThreadActivity extends AppCompatActivity {
    TextView tvShow1;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify_work);

        tvShow1 = (TextView) findViewById(R.id.tvShow1);
        new WorkThread1().start();

    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.btnNotify1:
                Message msg = handler.obtainMessage();
                msg.obj = "给 用户线程的消息。";
                handler.sendMessage(msg);
                break;
        }
    }


    class WorkThread1 extends Thread {

        @Override
        public void run() {
            Log.e("pzl", "子线程：" + Thread.currentThread().getName() + " run() start");
            Looper.prepare();
            handler = new MyHandler(Looper.myLooper());
            Looper.loop();
            Log.e("pzl", "子线程：" + Thread.currentThread().getName() + " run() end");
        }

        class MyHandler extends Handler {

            public MyHandler(Looper looper) {
                super(looper);
            }

            @Override
            public void handleMessage(Message msg) {//将在子线程中调用
                super.handleMessage(msg);
                Log.e("pzl", "handleMessage start 当前线程：" + Thread.currentThread().getName());
                int i = 0;
                while (i <= 10) {
                    i++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e("pzl", (String) msg.obj + " " + i);
                }
                Log.e("pzl", "handleMessage end 当前线程：" + Thread.currentThread().getName());
            }
        }

    }


}
